import util from '../../../utils/utils';
import data from '../../../utils/data.js';
import User from '../../../utils/user.js';
import {
  walktohomeHttp
} from '../../../api/walktohome.js';
const walktohomeModel = new walktohomeHttp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    hootGoods: [],
    shareImgUrl: "",
    ekey: '',
    shareImage: {},
    goods_id: 0,
    isCopy: false,
    copyText: '',
    goods: {},
    shareInfo: '',
    selectShareImage: 0,
    requestShareInfo: false,
    showShareDialog: false
  },

  initPage: function() {
    this.shareImage = new util.HashMap();
    this.httpGetRecommend()
    this.getUser();
  },
  //获取热门推荐
  httpGetRecommend() {
    let self = this;
    walktohomeModel.GetRecommend({}).then((res) => {
      self.setData({
        hootGoods: res.goods_list
      })
    });
  },
  //获取用户信息
  getUser() {
    let self = this;
    self.getUserInfo(function(res) {
      self.setData({
        ekey: res.ekey
      })
    })
  },

  //自定义分享
  onShareAppMessage: function(res) {
    let {
      ekey,
      goods,
      selectShareImage,
      shareInfo
    } = this.data
    if (res.from == "button") {
      return {
        title: goods.goods_name,
        imageUrl: shareInfo.GoodsImageURL[selectShareImage],
        path: '/pages/goods/detail/detail?id=' + goods.goods_id + '&ekey=' + ekey
      }
    }
  },
  /**
   * 打开分享弹窗
   */
  openShare: function(e) {
    let self = this;
    let goods = e.target.dataset.goods
    //如果点击的不是同一个商品则从新请求
    if (goods.goods_id != self.data.goods_id) {
      this.setData({
        shareInfo: false
      })
    }
    this.setData({
      goods: goods,
      goods_id: goods.goods_id
    })
    if (goods.unsale) {
      return;
    }
    if (util.fixInt(goods.platform_type) === 2) {
      util.msg('由于小程序不支持淘宝商品，请下载或打开巷友app体验');
      return;
    }
    self.getUserInfo(function(result) {
      self.setPath();
      let channel = User.getShareParam(0);
      if (!self.data.shareInfo) {
        self.setData({
          requestShareInfo: true,
        });
        util.request({
          url: util.api.PreShare,
          data: {
            shareId: channel.shareUid,
            aid: self.data.aid,
            userId: result.uid,
            goods_id: goods.goods_id
          },
          handle: true,
          callback: function(result) {
            let _copyText = [];
            let _data = result.res;
            _copyText.push(_data.GoodsName);
            _copyText.push('-------------------------------');
            _copyText.push('拼团价：¥' + _data.MinNormalPrice);
            _copyText.push('券后内部价：¥' + _data.PostPrice);
            _copyText.push('已售出：' + _data.SalesTip);
            _copyText.push('-------------------------------');
            _copyText.push('【购买方式】');
            _copyText.push('点击领券链接购买：' + _data.ShortUrl);
            self.setData({
              requestShareInfo: false,
              shareInfo: _data,
              copyText: _copyText.join("\n"),
              showShareDialog: true
            });
            /**
             * 自动生成一张图
             */
            self.switchShareImage({
              currentTarget: {
                dataset: {
                  index: 0
                }
              }
            });
            if (!self.shareOption['imageUrl']) {
              self.shareOption['imageUrl'] = _data.GoodsImageURL[0];
            }
          },
          error: function(result) {
            self.setData({
              requestShareInfo: false
            });
          }
        });
      } else {
        self.setData({
          showShareDialog: true
        });
      }
    }, function() {
      self.setData({
        initUser: false
      });
    });
  },
  /**
   * 复制分享文字并下载图片
   * @param e
   */
  copyShareInfo: function(e) {
    let self = this;
    let type = e.currentTarget.dataset.type;
    let key = '';
    wx.setClipboardData({
      data: this.data.copyText
    });
    self.setData({
      isCopy: true,
    });
    if (type === '1' || type === '2') {
      key = type === '1' ? 'wx_url' : 'h5_url';
      self.getShareImage(self.data.selectShareImage, function(urls) {
        wx.previewImage({
          urls: [
            urls[key],
          ]
        });
      });
    }
  },
  setPath: function() {
    /**
     * 设置首页地址
     */
    let options = this.options;
    let homePath = '/pages/home/index/index?v=1';
    let sharePath = '/pages/goods/detail/detail?id=' + this.data.goods_id;
    this.channel = User.getShareParam(options.hasOwnProperty('uid') ? options['uid'] : 0);
    if (this.channel.shareUid > 0) {
      homePath += '&uid=' + this.channel.shareUid;
      sharePath += '&uid=' + this.channel.shareUid;
    } else {
      sharePath += '&uid=&ekey=';
      this.channel.ekey = '';
    }
    if (this.channel.ekey) {
      homePath += '&ekey=' + this.channel.ekey;
      sharePath += '&ekey=' + this.channel.ekey;
    }
    if (this.data.aid > 0) {
      sharePath += '&aid=' + this.data.aid;
    }
    this.shareOption['path'] = sharePath;
    this.setData({
      channel: this.channel,
      homePath: homePath
    });
    util.log('channel', this.channel);
    util.log('shareOption', sharePath);
  },

  closeShareDialog: function() {
    this.setData({
      showShareDialog: false
    });
  },
  switchShareImage: function(e) {
    let self = this;
    let index = e.currentTarget.dataset.index;
    self.setData({
      selectShareImage: index
    });
    self.shareOption['imageUrl'] = this.data.shareInfo.GoodsImageURL[index];
    /**
     * 主动拉取合成的海报图片
     */
    self.getShareImage(index);
  },


  /**
   * 获取合成的分享图片
   * @param index
   * @param callback
   */
  getShareImage: function(index, callback) {
    let self = this;
    let key = index;
    let urls = self.shareImage.get(key);
    if (urls) {
      callback && callback(urls);
    } else {
      self.setData({
        requestShareImg: true,
      });
      let channel = User.getShareParam(0);
      let param = {
        url_type: 1,
        goods_url: self.data.shareInfo.GoodsImageURL[index],
        goods_id: self.data.goods_id,
        aid: 0,
      };
      if (channel.shareUid > 0) {
        param['ownerUserId'] = channel.shareUid;
      }
      data.QrcodeUrlShera(param, function(result) {
        self.setData({
          requestShareImg: false,
        });
        if (result.status === 'ok') {
          self.shareImage.put(key, result.res);
          callback && callback(result.res);
        } else {
          util.msg(result.msg);
        }
      });
    }
  },
  onClosePopup: function(e) {
    let type = e.currentTarget.dataset.type;
    if (type === 'ServiceText') {
      this.setData({
        showServiceText: false
      });
    }
    if (type === 'ShareDialog') {
      this.setData({
        showShareDialog: false
      });
    }
  },


});
